<?php
/**
 * Created by PhpStorm.
 * User: xiong <1099446868@qq.com>
 * DateTime: 2018/10/31
 * TIME: 18:09
 */

namespace app\index\validate;


use think\Db;
use think\facade\Request;
use think\Validate;
use think\facade\Validate as staticValidate;
use app\lib\exception\ParameterException;

class BaseValidate extends Validate {

    protected $message = ['用户ID参数错误，必须是正整数'];

    public function goCheck() {
        //获取http参数并验证
        $request = Request::instance();
        $param = $request->param();
        $result = $this->batch()->check($param);
        if (!$result) {
            return [
                'istrue' => false,
                'msg'    => $this->getError()
            ];
        } else {
            return [
                'istrue' => true,
                'msg'    => '',
            ];
        }
    }

    //自定义验证规则
    protected function isNotEmpty($value, $rule = '', $data = '', $field = '') {
        if (empty($value)) {
            return false;
        } else {
            return true;
        }
    }

    protected function isPhone($value) {
        $rule = '^1(3|4|5|6|7|8)[0-9]\d{8}$^';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    //判断是否是 用户名|邮箱|手机
    protected function nei($value, $rule = '', $data = '', $field = '') {
        if (staticValidate::isEmail($value)) {
            return 'email';
        } else if (self::isPhone($value)) {
            return 'phone';
        } else if (staticValidate::length($value, 10)) {
            return 'username';
        } else {
            return false;
        }
    }

    /**
     * @param        $value  前端传来的标签数据  可能是不带逗号的单标签，也可能是逗号链接的多标签
     * @param string $rule
     * @param string $data
     * @param string $field
     * @return bool
     */
    protected function checkTags($value, $rule = '', $data = '', $field = '') {

        $tags = Db::name('tags')->field('tag')->select();   //待优化
        foreach ($tags as $v) {
            $allowtags[] = $v['tag'];
        }

        if (strpos($value, ',') === false) {
            if (!in_array($value, $allowtags)) {
                return false;
            }
            return true;
        } else {
            $arr = explode(',', $value);
            if (!is_array($arr)) {
                return false;
            } else {
                foreach ($arr as $v) {
                    if (!in_array($v, $allowtags)) {
                        return false;
                    }
                }
                return true;
            }
        }
    }
}